<template>
	<view class="content">
		<view class="title">
			<image src="../../static/左侧星@2x.png" mode="widthFix"></image>
			<text>{{title}}</text>
			<image src="../../static/右侧星@2x.png" mode="widthFix"></image>
		</view>
		<view class="title2">
			<text>{{text}}</text>
		</view>
		<input class="inputText" v-model="mainText" type="text" placeholder="请输入您的提示文字"/>
		<image class="mainImage" :style="taskImg?'width:49%':''"
			:src="tempFilePaths?tempFilePaths:'https://qzy6.oss-cn-shenzhen.aliyuncs.com/appletAssets/'+img+'.png'"
			mode="widthFix"></image>
		<image class="mainImage" v-show="taskImg" :style="taskImg?'width:49%':''"
			:src="taskImg?taskImg:'https://qzy6.oss-cn-shenzhen.aliyuncs.com/appletAssets/'+img+'.png'" mode="widthFix">
		</image>

		<button class="showAdBtn" @click="showJiLiAd">{{!taskImg&&!adNum?"看广告后开始制作":taskImg&&!adNum?"看广告后再次制作":!taskImg&&!!adNum?"开始制作":"再次制作"}}</button>
		<button v-show="taskImg" class="showAdBtn" style="marginTop:20px" @click="save">保存到相册</button>
	</view>

</template>

<script>
	import api from '../../api/api.js'
	import {
		setInfo,
		parseUserData
	} from '../../hook/auth.js'
	export default {
		data() {
			return {
				img: "123", //图片
				title: "123", //标题
				text: "123", //副标题
				fun: "", //调用的接口url
				tempFilePaths: "", //临时图片路径
				tempFileBase64: "", //临时图片
				taskImg: "", //生成的图片
				mainText:"",//描述文字
				adNum:0//算力额度
			}
		},
		methods: {
			//保存到相册
			save() {
				const that = this
				// 下载图片
				uni.downloadFile({
					url: that.taskImg,
					success: downloadResult => {
						if (downloadResult.statusCode === 200) {
							// 下载成功，保存图片到系统相册
							uni.saveImageToPhotosAlbum({
								filePath: downloadResult.tempFilePath,
								success: () => {
									uni.showToast({
										title: '图片保存成功'
									});
								},
								fail: () => {
									uni.showToast({
										title: '图片保存失败',
										icon: 'none'
									});
								}
							});
						} else {
							uni.showToast({
								title: '图片下载失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '图片下载失败',
							icon: 'none'
						});
					}
				});

			},
			//开始绘画
			play() {
				
				this.seleImg()
			},
			//提交任务
			submitQuery() {
				uni.showLoading({
					title: "生成中...",
					mask: true
				})
				const that = this
				let Fun =api[this.fun];
				
				Fun({
					"client_id": "269df937a80d49129bb08e568e315e0e",
					"socket_id": "admin9527",
					"params": {
						"image_path": that.tempFileBase64,
						"text": that.mainText
					},
					"options": {
						"source": "web",
						"lifo": false
					}
				}).then((res) => {
					console.log(res)
					that.taskImg = res
					uni.hideLoading()
				}).catch((err) => {
					uni.hideLoading()
				})
			},
			//选择图片
			async seleImg() {
				const that = this
				await uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					crop: {
						width: 512,
						height: 512
					},
					success: function(res) {
						console.log('选择的图片', res);
						that.tempFilePaths = res.tempFilePaths

						// 使用uni.getFileSystemManager().readFile方法读取文件内容
						const fileSystemManager = uni.getFileSystemManager();
						fileSystemManager.readFile({
							filePath: that.tempFilePaths[0], // 文件路径
							encoding: 'base64', // 编码格式为base64
							success: (res) => {
								// 成功读取文件后的回调
								that.tempFileBase64 = res.data; // 文件内容的base64
								that.submitQuery()
							},
							fail: (err) => {
								// 读取文件失败的回调
								console.error(err);
							}
						});
					}
				});

			},
			getUserAdNum(){
				let userData  = parseUserData()
				this.adNum  =  userData.adNum
				return userData.adNum
			},
			// 展示激励广告
			showJiLiAd() {
				//缺少提示词
				if(!this.mainText){
					uni.showToast({
						title:"请输入提示词",
						icon:"fail"
					})
					return
				}else{
					//有次数,开始制作
					if(this.getUserAdNum()>0){
						let userData  = parseUserData()
						userData.adNum-=1
						setInfo(userData)
						this.getUserAdNum()
						this.play()
					}else{
						//没有次数,开始看广告
						tt.showLoading();
						this.ad.show();
					}
				}
				
			},
			//展示弹窗广告
			showTanAd() {
				const interstitialAd = tt.createInterstitialAd({
					adUnitId: "2z89wsxvupdvrts7d8",
				});

				interstitialAd
					.load()
					.then(() => {
						interstitialAd.show().then(() => {
							console.log("广告显示成功");
						}).catch((err) => {
							console.error("广告组件加载出现问题", err);
						});
					})
					.catch((err) => {
						console.log("adUnitId:2z89wsxvupdvrts7d8", err);
					})
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option); //打印出上个页面传递的参数。
			this.img = option.img
			this.title = option.title
			this.text = option.text
			this.fun = option.fun
			this.getUserAdNum()

			//启动弹窗广告
			setTimeout(() => {
				// this.showTanAd()
			}, 1000)

			// 创建实例
			this.ad = tt.createRewardedVideoAd({
				adUnitId: "7y5va1nz0omqzzghuf",
			});

			// 监听错误
			this.ad.onError((err) => {
				tt.hideLoading();
				switch (err.errCode) {
					case 1004:
						// 无合适的广告
						break;
					default:
						// 更多请参考错误码文档
				}
			});

			// 监听视频播放完成
			this.ad.onClose((data) => {
				tt.hideLoading();
				if (data.isEnded) {
					console.log("观看了", data.count, "个视频");
					
					uni.showToast({
						title: "完成广告观看",
						icon: "success"
					})
					this.getUserAdNum()
					this.play()
				} else {
					uni.showToast({
						title: "未看完广告",
						icon: "error"
					})
					console.log("未观看完视频");
				}
			});


			// 预加载资源
			this.ad.load();
		},
		mounted() {}
	}
</script>

<style scoped>
	.inputText{
		background: #FFFFFF;
		height: 100px;
	}
	.showAdBtn {
		width: 80%;
		height: 48px;
		background: linear-gradient(90deg, #7800FF, #A600E5);
		border-radius: 24px;
		font-weight: 400;
		font-size: 14px;
		line-height: 48px;
		color: #FFFFFF;
	}

	.mainImage {
		max-height: 40%;
		width: 100%;
		margin-top: 20px;
	}

	.title2 {
		text-align: center;
		font-weight: 400;
		font-size: 12px;
		color: #9F9FA1;
		line-height: 20px;
	}

	.title text {
		margin: 0 10px;
		vertical-align: middle;
	}

	.title image {
		vertical-align: middle;
		width: 17px;
	}

	.title {
		line-height: 40px;
		text-align: center;
		font-weight: 400;
		font-size: 17px;
		color: #FFFFFF;
	}

	.content {
		width: 100%;
		height: 100vh;
		padding-top: 30px;
		box-sizing: border-box;
		background-color: #000000;
	}
</style>